// @flow
import React from 'react'
import { Tree, Input, Icon } from 'antd'
// import moment from 'moment'
import { withRouter } from 'react-router'
import styles from './GlobalBOM.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { saveDeviceData } from 'store/modules/deviceCard'
import { connect } from 'react-redux'
import R from 'ramda'
const TreeNode = Tree.TreeNode
const Search = Input.Search

type Props = {
  saveDeviceData: Function,
  history: Object,
  data: Object,
  userId: string
}

type States = {
  visible: boolean,
  bomDataAll: Array<Object>,
  bomData: Array<Object>,
  searchValue: string,
  expandedKeys: Array<string>,
  autoExpandParent: boolean,
  dataList: Array<Object>,
  deviceStatus: Array<Object>
}

class GlobalBOM extends React.Component {
  state: States
  props: Props
  getBomData: Function
  togglePop: Function
  onSelect: Function
  getSearchValue: Function
  onExpand: Function
  generateList: Function
  getParentKey: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      visible: false,
      bomDataAll: [],
      bomData: [],
      searchValue: '',
      expandedKeys: [],
      autoExpandParent: true,
      dataList: [],
      deviceStatus: []
    }
    this.getBomData = this.getBomData.bind(this)
    this.togglePop = this.togglePop.bind(this)
    this.onSelect = this.onSelect.bind(this)
    this.getSearchValue = this.getSearchValue.bind(this)
    this.onExpand = this.onExpand.bind(this)
    this.generateList = this.generateList.bind(this)
    this.getParentKey = this.getParentKey.bind(this)
  }
  componentWillMount () {
    const { userId } = this.props
    this.getBomData(userId)
    // 在字典中取设备状态，判断设备机组中点点的颜色
    universalFetch(`${__SERVICE_API__}sys/dicts?type=deviceStatus`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        deviceStatus: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  componentWillReceiveProps (nextProps) {
    if (!R.equals(nextProps, this.props)) {
      const { userId } = nextProps
      this.getBomData(userId)
    }
  }
  getBomData (userId) {
    if (!userId) {
      return
    }
    universalFetch(`${__SERVICE_API__}device/systree/sys?userId=${userId}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          bomDataAll: json.result,
          bomData: json.result
        })
        this.generateList(json.result)
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  togglePop () {
    this.setState({
      visible: !this.state.visible
    })
  }

  onSelect (selectedKeys, info) {
    // console.log('selected', selectedKeys, info)
    const { saveDeviceData, history } = this.props
    const { data } = info.node.props
    if (data.customerNo) { // 客户层
      universalFetch(`${__SERVICE_API__}device/customers/${data.id}`)
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          const result = json.result
          const location = {
            pathname: '/device-card',
            state: {
              data: result,
              groupId: result.id,
              groupName: result.name,
              longitude: result.region.longitude,
              latitude: result.region.latitude,
              count: result.count
            }
          }
          history.push(location)
          // this.setState({
          //   visible: false
          // })
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
        })
    }
    if (data.deviceNo) { // 设备层
      universalFetch(`${__SERVICE_API__}device/devices/${data.id}`)
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          // saveGroupId(json.result.id)
          saveDeviceData(json.result)
          history.push(`/device-file/`) // 解决同页面不刷新的bug
          history.push(`/device-file/${data.id}/overview`)
          // this.setState({
          //   visible: false
          // })
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
        })
    }
    if (data.deviceId) { // 测点层
      universalFetch(`${__SERVICE_API__}device/devices/${data.deviceId}`)
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          saveDeviceData(json.result)
          let variable = 'direc' // 振动量默认是通频值
          if (data.nameEn === 'c_sta') { // 过程量默认是位移value
            variable = 'value'
          }
          const location = {
            pathname: `/device-file/${data.deviceId}/condition`,
            state: {
              defaultActiveKey: 'dynamicTab',
              dynamicIndicator: data.nameEn + '___' + variable,
              defaultChannel: [data.channelId + '__' + data.name]
            }
          }
          history.push(`/device-file/`) // 解决同页面不刷新的bug
          history.push(location)
          // this.setState({
          //   visible: false
          // })
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
        })
    }
  }
  getSearchValue (e) {
    const component = this
    const { bomDataAll, dataList } = this.state
    const value = e.target.value
    // const expandedKeys = dataList.map((item) => {
    //   if (item.key.indexOf(value) > -1) {
    //     return component.getParentKey(item.key, bomData)
    //   }
    //   return null
    // }).filter((item, i, self) => item && self.indexOf(item) === i)
    // 首层搜索
    const reg = new RegExp(value, 'gi')
    this.setState({
      bomData: bomDataAll.map((record) => {
        let match = record.name.match(reg) // 搜索名字
        if (!match) {
          // record.treeList.map((d) => {
          //   match = d.name.match(reg)
          //   if (match) {
          //     return
          //   }
          // })
          if (!match) {
            return false
          }
        }
        return {
          ...record
        }
      }).filter(record => !!record),
      // expandedKeys,
      searchValue: value,
      autoExpandParent: true
    })
  }

  onExpand (expandedKeys) {
    this.setState({
      expandedKeys,
      autoExpandParent: false
    })
  }

  getParentKey (id, tree) {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i]
      if (node.treeList) {
        if (node.treeList.some(item => item.id === id)) {
          parentKey = node.id
        } else if (this.getParentKey(id, node.treeList)) {
          parentKey = this.getParentKey(id, node.treeList)
        }
      }
    }
    return parentKey
  }

  generateList (data) {
    const { dataList } = this.state
    for (let i = 0; i < data.length; i++) {
      const node = data[i]
      let arr = R.clone(dataList)
      arr.push({ key: String(node.id), title: node.name })
      this.setState({
        dataList: arr
      })
      if (node.children) {
        this.generateList(node.children, node.key)
      }
    }
  }

  render () {
    const { visible, bomData, searchValue, expandedKeys, autoExpandParent, deviceStatus } = this.state
    const bomHeight = document.body.scrollHeight - 80
    const loop = data => data.map((item) => {
      if (item) {
        const index = item.name.search(searchValue)
        const beforeStr = item.name.substr(0, index)
        const afterStr = item.name.substr(index + searchValue.length)
        let stateDisplay = 'none' // 状态是否显示
        let color = '#000' // 状态的颜色
        if (item.status) {
          stateDisplay = 'inline'
          let deviceS = deviceStatus.filter((dd) => dd.value === item.status)
          if (deviceS.length > 0) {
            color = deviceS[0].color
          }
        }

        const name = index > -1 ? (
          <span><span style={{ color: color, marginRight: 5, display: stateDisplay }}>●</span>
            {beforeStr}
            <span style={{ color: '#f50' }}>{searchValue}</span>
            {afterStr}
          </span>
        ) : <span><span style={{ color: color, marginRight: 5, display: stateDisplay }}>●</span>{item.name}</span>
        if (item.treeList && item.treeList.length > 0) {
          return (
            <TreeNode key={String(item.id + '__' + item.name)} title={name}
              data={item}
              >
              {loop(item.treeList)}
            </TreeNode>
          )
        }
        return <TreeNode key={String(item.id + '__' + item.name)} title={name}
          data={item}
          />
      }
    })
    return (
      <div className={styles['bell']}>
        <i className='fa fa-th-list'
          aria-hidden='true'
          style={{ position: 'relative', cursor: 'pointer' }}
          onClick={this.togglePop} />
        {
          visible ? <Icon type='caret-up' className={styles['bellIcon']} /> : ''
        }
        {
          visible ? <div className={styles['bellPop']} style={{ height: bomHeight }}>
            {
              // <Search placeholder='搜索' onChange={this.getSearchValue} />
            }
            <Tree
              showLine
              onExpand={this.onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              onSelect={this.onSelect}
            >
              {
                loop(bomData)
              }
            </Tree>
          </div> : ''
        }
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStateToProps, { saveDeviceData })(withRouter(GlobalBOM))
